{% extends "base.html" %}

{% block navbar %}
  {# no navbar on observation page #}
{% endblock navbar %}

{% block main_content %}
  <div class="well well-lg">
    <div id="tweet"></div>
  </div>
{% endblock main_content %}

{% block page_scripts %}
  <script src="https://fb.me/react-15.1.0.js"></script>
  <script src="https://fb.me/react-dom-15.1.0.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
  <script src="{{url_for('static', filename='js/queue.js')}}"></script>
  <script type="text/babel">
    var TweetDisplay = React.createClass({
      getInitialState: function() {
        //initialize queue
        this.q = new Queue();

        //set up event source
        this.source = new EventSource("{{url_for('home.tweets', key=camp_key)}}");
        this.source.onmessage = this.processTweet;

        //set up polling interval
        window.setInterval(this.checkQueue, 500);

        //return initial state
        return ({id: 0});
      },

      processTweet: function(e){
        this.q.enqueue(JSON.parse(e.data));
        //console.log('enqueue: '+e.data);
      },

      cleanText: function(t){
        return t.replace(/#/g,'hashtag ')          //say "hashtag"
                .replace(/https?:\/\/\S+/ig, '')   //don't read urls
                .replace(/brbtb/ig, "burb terb ")  //pronouce the invisible r in brbtb
                .replace(/COVID\-?/ig,'covid ')         //say COVID instead of C-O-V-I-D
      },

      checkQueue: function(){
        if (window.speechSynthesis.speaking){
          //console.log("speaking");
          return;
        }

        //skip if queue is empty
        if (this.q.isEmpty()){
          //console.log('queue empty');
          this.replaceState({id: 0});
          return;
        }

        //update widget
        var tweet = this.q.dequeue();
        //console.log('dequeue: '+tweet);
        this.replaceState(tweet);

        //read tweet
        window.speechSynthesis.speak(
          new SpeechSynthesisUtterance(this.cleanText(tweet.text))
        );
      },

      render: function() {
        console.log('rendering: '+this.state.id)
        if (this.state.id == 0) {
            return( <div /> );
        }else{
          return (
            <div className="container">
              <div className="row">
                <div className="col-md-4 text-right">
                  <img src={this.state.image_url} />
                  <div className="text-muted">
                    @{this.state.username}
                  </div>
                </div>
                <div className="col-md-4">
                  {this.state.text}
                </div>
              </div>
            </div>
          );
        }
      },
    });

    ReactDOM.render(
      <TweetDisplay campaign="{{camp_key}}" />,
      document.getElementById('tweet')
    );
  </script>
{% endblock page_scripts %}
